var addressGraphicLayer;
var roomGraphicLayer;
var initAddressSearch;
var addressSearchText;
var localStorage = window.localStorage;
var isAddressSearch = false
var clearRoomList

require([
    "dojo/on", "dojo/_base/connect",
    "esri/symbols/PictureMarkerSymbol", "esri/layers/GraphicsLayer",
    "esri/graphic", "esri/InfoTemplate",
    "esri/geometry/Point",
    "dojo/domReady!"
], function (
    on, connect, PictureMarkerSymbol, GraphicsLayer, Graphic,
    InfoTemplate, Point) {

    initAddressSearch = function () {
        addressGraphicLayer = new GraphicsLayer({
            id: "addressGraphicLayer"
        });
        map.addLayer(addressGraphicLayer);
        roomGraphicLayer = new GraphicsLayer({
            id: "roomGraphicLayer"
        });
        map.addLayer(roomGraphicLayer);

        addressGraphicLayer.on("click", function (e) {
            aroundSearchCenterGraphic = e.graphic
            map.infoWindow.hide();
        })

        if (localStorage.getItem("historyAddressArray") == null) {
            localStorage.setItem("historyAddressArray", JSON.stringify([]));
        }
    }

    //历史搜索记录
    $("#menpaiInput").click(function () {
        showHistoryList()
    })

    function showHistoryList() {
        const a = $("#menpaiInput").val();
        if ($("#menpaiInput").val() !== "") {
            return
        }
        $("#historyaAdressList>ul").empty();

        let historyAddressArray = JSON.parse(localStorage.getItem('historyAddressArray'));

        if (historyAddressArray.length > 0) {
            $("#historyaAdressList").show()
            $(".divide1").show()

            historyAddressArray.reverse().forEach((item, index) => {
                var li = document.createElement("li");
                li.id = "historyitem_" + index;
                var corp_name = document.createElement("p");
                corp_name.className = "history_item";
                corp_name.innerHTML = `<img class='historyImg' src='img/history record.png'/>${item}
                                     <a id='del_history_${index}' class='close'>×</a>`;
                li.appendChild(corp_name);
                $("#historyaAdressList>ul").append(li);

                $(li).click(function () {
                    $("#menpaiInput").val(item)
                    doAddressSearch(item)
                })

                $(`#del_history_${index}`).click(function (e) {
                    historyAddressArray.splice(index, 1)
                    localStorage.setItem('historyAddressArray', JSON.stringify(historyAddressArray.reverse()));
                    showHistoryList()
                    e.stopPropagation();
                })
            })

            var li = document.createElement("li");
            li.id = "historyEmpty";
            var corp_name = document.createElement("p");
            corp_name.className = "history_item";
            corp_name.innerHTML = `清除所有历史记录`;

            li.appendChild(corp_name);
            $("#historyaAdressList>ul").append(li);

            $(li).click(function () {
                localStorage.setItem("historyAddressArray", JSON.stringify([]));
                showHistoryList()
            })
        }

    }

    $(".input_clear").click(function () {
        closePanel()
        $("#addressSearchBtn").hide();
        $("#addressSearchPanel").show();
        resetBtnPosition()
    })


    //地址检索
    $("#addressSearchBtn").click(function () {
        $("#addressSearchBtn").hide();
        $("#addressSearchPanel").show();
        resetBtnPosition()
    });

    $("#menpaiInput").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#menpaiSearBtn").click();
        }
    })

    var addressResult = [];
    $("#menpaiSearBtn").click(function () {
        addressSearchText = $("#menpaiInput").val();
        if (addressSearchText.trim().length === 0) {
            $("#menpaiInput").focus();
            return;
        }
        doAddressSearch(addressSearchText)
    });

    function doAddressSearch(addressSearchText) {
        //存储搜索历史
        historyAddressArray = JSON.parse(localStorage.getItem('historyAddressArray'));

        function isInHistoryAddressArray(text) {
            return text === addressSearchText;
        }
        const index = historyAddressArray.findIndex(isInHistoryAddressArray);
        if (index !== -1) {
            historyAddressArray.splice(index, 1)
        }
        historyAddressArray.push(addressSearchText)
        localStorage.setItem('historyAddressArray', JSON.stringify(historyAddressArray));

        $("#historyaAdressList").hide()
        $(".divide1").hide()
        $("#addressList>ul").empty();
        $("#addressList .waitPanel").show();
        $("#addressPage").empty();
        clearRoomList()

        $.ajax({
            // url: oneMapServerIPproxy+"/OneMapServer/rest/services/address_p/as_CH.asmx/ASCH_AddressSearch?vSearch_word=" + addressSearchText + "&vResult_count=1000&token=" + GLOBAL_TOKEN,
            url: addressSearchUrl + addressSearchText,
            type: "get",
            dataType: "json",
            success: function (response) {
                map.infoWindow.hide();
                $("#addressList").show();
                $("#addressList .waitPanel").hide();
                $(".text-center").show();
                $(".divide1").show()

                addressResult = response.data;

                if (addressResult.length == 0) {
                    var sli = `<li>
                    <span class='data_count'>在上海市范围内未找到相关地点。</span>
                    </li>`
                    $("#addressList>ul").append(sli);
                    $(".text-center").hide();
                    $(".divide1").hide()
                    $(".error_report").click(function (e) {
                        openReportPanel(e)
                    })
                } else if (addressResult.length > 0) {
                    $("#addressPage").initPage(addressResult.length, 1, buildAddress);
                }
            }
        });
    }

    var onePageCount = 10
    var zoomLevel = 8
    //构建搜索结果内容
    function buildAddress(page) {
        isAddressSearch = true

        $("#addressList>ul").empty();
        var sli = `<li>
                <span class='data_count'>搜索到 <b>${addressResult.length}</b> 条结果</span>
            </li>`
        $("#addressList>ul").append(sli);
        addressGraphicLayer.clear();
        addressGraphicLayer.show();
        roomGraphicLayer.hide();

        var max = page * onePageCount;

        if (max > addressResult.length) {
            max = addressResult.length
        }

        // let addressGraphics = []
        for (let i = (page - 1) * onePageCount; i < max; i++) {
            var item = addressResult[i];
            var attr = {};

            const {
                pointX,
                pointY,
                resultAccuracy,
                address,
                poiString,
                regionQx,
                regionJd,
                regionJw,
                roomList,
                verifyName,
                resultType,
                roadName1,
                roadName2
            } = item

            const area = `${regionQx}-${regionJd}-${regionJw}`

            var displayName
            switch (resultType) {
                case "门牌":
                    displayName = poiString || address
                    // displayName = address
                    break;
                case "POI":
                    displayName = poiString
                    break;
                case "道路":
                    displayName = verifyName
                    break;
                case "道路交叉口":
                    displayName = roadName1 + roadName2 + "交叉口"
                    break;

                default:
                    displayName = poiString || address
                    break;
            }

            // attr["name"] = address;
            // attr["district"] = area;
            attr["x"] = pointX;
            attr["y"] = pointY;
            // attr["maccuracy"] = resultAccuracy;

            // var infoCont = "<div class='infoCont'>";
            // // infoCont += "区县" + ": " + area + " <br/>";
            // infoCont += area + " <br/>";
            // infoCont += `<div id='aroundSearchBtn' class='aroundSearchBtn'><img width='20px' src='img/icon-nearby.png'>周边查询</div>`;

            var sms = new PictureMarkerSymbol("img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png", 30, 30).setOffset(0, 15);
            var pt = new Point(pointX, pointY, map.spatialReference);
            if (address !== null && address.trim() !== "") {
                var infoCont = `<div class='infoCont'>
                            ${address}<br/>
                            ${area}<br/>
                            <div id='aroundSearchBtn' class='aroundSearchBtn'><img width='20px' src='img/icon-nearby.png'>周边查询</div>
            `;
            } else {
                var infoCont = `<div class='infoCont'>
                            ${area}<br/>
                            <div id='aroundSearchBtn' class='aroundSearchBtn'><img width='20px' src='img/icon-nearby.png'>周边查询</div>
            `;
            }

            var infoTemplate = new InfoTemplate("<b>" + displayName + "</b>", infoCont);
            var graphic = new Graphic(pt, sms, attr, infoTemplate);

            addressGraphicLayer.add(graphic);
            // addressGraphics.push(graphic)

            var li = document.createElement("li");


            var corp_name = document.createElement("p");
            corp_name.className = "corp_name";
            corp_name.innerHTML = "<img height='25px' src='img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png'/>" + "&nbsp" + displayName;
            if (roomList !== null) {
                corp_name.innerHTML += `<span class="roomListSpan" num="${i}">共${roomList.length}户</span>`
            }
            li.appendChild(corp_name);

            if (address !== null && address.trim() !== "") {
                var address_div = document.createElement("p");
                address_div.className = "address_name";
                address_div.innerHTML = `<span>${address}</span>`;
                li.appendChild(address_div);
            }

            var xzqh_div = document.createElement("p");
            xzqh_div.className = "xzqh_name";
            xzqh_div.innerHTML = `<span>${area}</span>`;
            li.appendChild(xzqh_div);

            $("#addressList>ul").append(li);

            //第一个点直接聚焦
            if (i - (page - 1) * onePageCount == 0) {
                const center = new Point(pointX * 1, pointY * 1, map.spatialReference);
                map.infoWindow.hide();
                map.infoWindow.setContent(graphic.getContent());
                map.infoWindow.setTitle(graphic.getTitle());
                map.infoWindow.show(pt);
                map.centerAndZoom(center, zoomLevel);

                $('#addressList li').removeClass('activeli');
                $('#addressList li:nth-child(2)').addClass('activeli');

                aroundSearchCenterGraphic = graphic;
            }

            (function (li, arg, idx, g) {
                on(li, "click", function () {
                    $('#addressList li').removeClass('activeli');
                    $(li).addClass('activeli');

                    map.graphics.clear();

                    var pt = new Point(arg.x * 1, arg.y * 1, map.spatialReference);
                    var center = new Point(arg.x * 1, arg.y * 1, map.spatialReference);
                    map.infoWindow.hide();
                    map.infoWindow.setContent(g.getContent());
                    map.infoWindow.setTitle(g.getTitle());
                    map.infoWindow.show(pt);
                    map.centerAndZoom(center, zoomLevel);

                    aroundSearchCenterGraphic = g
                });
            })(li, attr, i, graphic);
        }

        $(".address_name span").click(function (e) {
            console.log(e)
            const searchWord = e.currentTarget.innerText
            doAddressSearch(searchWord)
            $("#menpaiInput").val(searchWord)
            e.stopPropagation()
        })
        $(".error_report").click(function (e) {
            openReportPanel(e)
        })


        //构建户号搜索结果内容
        var curRoomList
        var addressListNum
        $(".roomListSpan").click(function (e) {
            $("#addressList").hide()
            $("#roomList").show()
            $("#backToAddressList").show()
            $("#roomPage").show()
            $("#addressPage").hide()
            addressListNum = e.currentTarget.attributes[1].nodeValue
            curRoomList = addressResult[addressListNum].roomList
            addressSearchText = $("#menpaiInput").val()
            $("#backToAddressList").html(`<i class="fa fa-chevron-left"></i> &nbsp返回 “${addressSearchText}”的搜索结果`)

            if (curRoomList.length > 0) {
                $("#roomPage").initPage(curRoomList.length, 1, buildRoomList);
            }

            e.stopPropagation()
        })

        //构建搜索结果内容
        function buildRoomList(page) {
            isAddressSearch = true

            $("#roomList>ul").empty();
            var sli = "<li><span class='data_count'>共有" + curRoomList.length + "条结果</span>" +
                "</li>"
            $("#roomList>ul").append(sli);
            roomGraphicLayer.clear();
            roomGraphicLayer.show();
            addressGraphicLayer.hide();

            var max = page * onePageCount;

            if (max > curRoomList.length) {
                max = curRoomList.length
            }

            for (let i = (page - 1) * onePageCount; i < max; i++) {
                var item = curRoomList[i];
                var attr = {};

                const {
                    pointX,
                    pointY,
                    poiString,
                    regionQx,
                    regionJd,
                    regionJw,
                    dataSource,
                    floor,
                    roomNo
                } = item
                const wholeAddress = addressResult[addressListNum].address + roomNo + "室"

                const area = `${regionQx}-${regionJd}-${regionJw}`
                // attr["name"] = address;
                // attr["district"] = area;
                attr["x"] = pointX;
                attr["y"] = pointY;
                // attr["maccuracy"] = resultAccuracy;

                // var infoCont = "<div class='infoCont'>";
                // // infoCont += "区县" + ": " + area + " <br/>";
                // infoCont += area + " <br/>";
                // infoCont += `<div id='aroundSearchBtn' class='aroundSearchBtn'><img width='20px' src='img/icon-nearby.png'>周边查询</div>`;

                var sms = new PictureMarkerSymbol("img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png", 30, 30).setOffset(0, 15);
                var pt = new Point(pointX, pointY, map.spatialReference);
                if (floor) {
                    var infoCont = `<div class='infoCont'>
                    所在层数：${floor}层<br/>
                                ${area}<br/>
                    `;
                } else {
                    var infoCont = `<div class='infoCont'>
                            ${area}<br/>
                `;
                }

                var infoTemplate = new InfoTemplate("<b>" + wholeAddress + "</b>", infoCont);
                var graphic = new Graphic(pt, sms, attr, infoTemplate);

                roomGraphicLayer.add(graphic);
                // addressGraphics.push(graphic)

                var li = document.createElement("li");
                var corp_name = document.createElement("p");
                corp_name.className = "corp_name";
                corp_name.innerHTML = "<img height='25px' src='img/marker2/" + (i + 1 - (page - 1) * onePageCount) + ".png'/>" + "&nbsp" + wholeAddress;
                li.appendChild(corp_name);

                var room_div = document.createElement("p");
                room_div.className = "xzqh_name";
                room_div.innerHTML = `户号：${roomNo}室`;
                li.appendChild(room_div);

                if (floor) {
                    var floor_div = document.createElement("p");
                    floor_div.className = "xzqh_name";
                    floor_div.innerHTML = `所在层数：${floor}层`;
                    li.appendChild(floor_div);
                }

                var xzqh_div = document.createElement("p");
                xzqh_div.className = "xzqh_name";
                xzqh_div.innerHTML = area;
                li.appendChild(xzqh_div);

                const dataSource1 = dataSource.substring(0, dataSource.indexOf("("))
                var address_div = document.createElement("p");
                address_div.className = "xzqh_name";
                address_div.innerHTML = `数据来源：${dataSource1}`;
                li.appendChild(address_div);

                $("#roomList>ul").append(li);

                //第一个点直接聚焦
                if (i - (page - 1) * onePageCount == 0) {
                    const center = new Point(pointX * 1, pointY * 1, map.spatialReference);
                    map.infoWindow.hide();
                    map.infoWindow.setContent(graphic.getContent());
                    map.infoWindow.setTitle(graphic.getTitle());
                    map.infoWindow.show(pt);
                    map.centerAndZoom(center, zoomLevel);

                    $('#roomList li').removeClass('activeli');
                    $('#roomList li:nth-child(2)').addClass('activeli');

                    aroundSearchCenterGraphic = graphic;
                }

                (function (li, arg, idx, g) {
                    on(li, "click", function () {
                        $('#roomList li').removeClass('activeli');
                        $(li).addClass('activeli');

                        map.graphics.clear();

                        var pt = new Point(arg.x * 1, arg.y * 1, map.spatialReference);
                        var center = new Point(arg.x * 1, arg.y * 1, map.spatialReference);
                        map.infoWindow.hide();
                        map.infoWindow.setContent(g.getContent());
                        map.infoWindow.setTitle(g.getTitle());
                        map.infoWindow.show(pt);
                        map.centerAndZoom(center, zoomLevel);

                        aroundSearchCenterGraphic = g
                    });
                })(li, attr, i, graphic);
            }

        }

    }

    $("#backToAddressList").click(function (e) {
        clearRoomList()
    })

    $("#reportBtn").click(function (e) {
        alert("提交成功")
        clearReportPanel()
    })

    // $(".reportPanel .close").click(function (e) {
    //     clearReportPanel()
    // })


    // function openReportPanel(e) {
    //     clearReportPanel()
    //     const text = e.currentTarget.innerText
    //     console.log(text)
    //     if (text === "反馈") {
    //         const addressListNum = e.currentTarget.attributes[1].nodeValue
    //         const {
    //             address,
    //             poiString
    //         } = addressResult[addressListNum]
    //         $(".reportForm input")[0].value = poiString
    //         $(".reportForm input")[1].value = address
    //     }

    //     $(".reportPanel").show()
    // }

    // function clearReportPanel() {
    //     $(".reportPanel").hide()
    //     $(".reportForm input").val("")
    //     $(".reportForm textarea").val("")
    // }

    clearRoomList = function () {
        $("#addressList").show()
        $("#roomList").hide()
        $("#backToAddressList").hide()
        $("#roomPage").hide()
        $("#addressPage").show()
        roomGraphicLayer.hide();
        addressGraphicLayer.show();
        map.infoWindow.hide();
    }

});